package com.hao.crm.util;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hao.crm.domain.Employee;
import com.hao.crm.domain.Permission;
import com.hao.crm.service.IPermissionService;

@Component
public class PermissionUtil {
	private static IPermissionService permissionService;
	@Autowired
	public void setPermissionService(IPermissionService permissionService) {
		PermissionUtil.permissionService = permissionService;
	}

	public static boolean checkPermission(String function) {
		HttpSession session = UserContext.get().getSession();
		Employee user = (Employee) session.getAttribute(UserContext.USER_IN_SESSION);
		if(user.getAdmin()) {
			return true;
		}
		Permission p = permissionService.selectByResouce(function);
		if(p!=null) {
			String allFunction = function.split(":")[0]+":"+"All";
			List<Permission> pers = (List<Permission>) session.getAttribute(UserContext.PERMISSION_IN_SESSION);
			for (Permission permission : pers) {
				if(permission.getResource().equals(function)||permission.getResource().equals(allFunction)) {
					return true;
				}
			}
			return false;
		}else {
			return true;
		}
	}

}
